package org.example.service;

import org.example.listener.RedisSubscriber;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.stereotype.Service;

@Service
public class RedisMessageService {

    private final RedisTemplate<String, Object> redisTemplate;

    public RedisMessageService(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    public void publishMessage(String topic, String message) {
        redisTemplate.convertAndSend(topic, message);
    }

    // 广播消息到 Redis 主题
    public void broadcastMessage(String topic, String message) {
        redisTemplate.convertAndSend(topic, message);
    }

    @Bean
    RedisMessageListenerContainer redisContainer(RedisConnectionFactory connectionFactory) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        return container;
    }

    @Bean
    MessageListenerAdapter messageListener() {
        return new MessageListenerAdapter(new RedisSubscriber());
    }
}

/*class RedisSubscriber implements MessageListener {

    @Override
    public void onMessage(Message message, byte[] pattern) {
        // 收到消息后的处理逻辑
        String body = new String(message.getBody(), StandardCharsets.UTF_8);
        System.out.println("收到消息: " + body);
    }
}*/

